#include <errno.h>
#include <string.h>
#include <stdio.h>

/**
 *  Demonstrates the error handling with the help of errno, perror() and strerror
 * 
 *  name    errno_test.c
 *  version 1.0
 *  author  Benjamin Friedrich (pib.benjamin.friedrich@htw-saarland.de)
 */
int main()
{
  // activates an error by using "invalid mode" instead of "r", "r+",.. 
  FILE *file = fopen("test_file.txt","invalid mode");
  
  // if fopen returns NULL there has been an error
  if(file == NULL)
  {
     /* it is recommended to store the errno if perror() is not called directly after an occured error, because the value
        of errno is not defined after a successful call of a library function. So it is possible the value of errno could be
        changed by such a other function call.*/
     int savedErrNo = errno;

     // prints the error message with perror()
     perror("fopen (perror)");

     // handles the error message with strerror(). 
     char *errorMessage = strerror(savedErrNo);
     printf("fopen (strerror): %s\n",errorMessage);

     // error handling depending on the occured error
     switch(savedErrNo)
     {
	case EINVAL: printf("fopen (EINVAL): invalid mode as it is mentioned in the man page of fopen\n");
                     break;
        default:     printf("fopen: Any other error: %i\n",savedErrNo);
     }

     // signalises there has been an error
     return 1;
  }  

  // there has not been any error...  
  fprintf(file, "no idea how this work...");
  fclose(file);  
  
  return 0;
}